package org.expressme.ant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;

import org.apache.tools.ant.BuildException;

public class Utils {

    private static final Map<Class<?>, String> mapping = new HashMap<Class<?>, String>();

    /**
     * Default mapping. See:
     * http://livedocs.adobe.com/blazeds/1/blazeds_devguide/help.html?content=serialize_data_3.html
     */
    static {
        mapping.put(String.class, "String");

        mapping.put(boolean.class, "Boolean");
        mapping.put(Boolean.class, "Boolean");

        mapping.put(int.class, "int");
        mapping.put(Integer.class, "int");

        mapping.put(short.class, "int");
        mapping.put(Short.class, "int");

        mapping.put(Byte.class, "int");
        mapping.put(byte.class, "int");

        mapping.put(double.class, "Number");
        mapping.put(Double.class, "Number");

        mapping.put(long.class, "Number");
        mapping.put(Long.class, "Number");

        mapping.put(float.class, "Number");
        mapping.put(Float.class, "Number");

        mapping.put(char.class, "String");
        mapping.put(Character.class, "String");

        mapping.put(char[].class, "String");
        mapping.put(Character[].class, "String");

        mapping.put(BigInteger.class, "String");
        mapping.put(BigDecimal.class, "String");

        mapping.put(Calendar.class, "Date");
        mapping.put(Date.class, "Date");

        mapping.put(Object[].class, "Array");
        mapping.put(Collection.class, "mx.collections.ArrayCollection");

        mapping.put(Map.class, "Object");
        mapping.put(Dictionary.class, "Object");

        mapping.put(byte[].class, "flash.utils.ByteArray");
    }

    public static String getMapping(Class<?> clazz) {
        return mapping.get(clazz);
    }

    public static String loadResource(String resource) {
        StringBuilder sb = new StringBuilder(1024);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(Utils.class.getClassLoader().getResourceAsStream(resource), "UTF-8"));
            for (;;) {
                String s = reader.readLine();
                if (s==null)
                    break;
                sb.append(s).append("\r\n");
            }
            return sb.toString();
        }
        catch (IOException e) {
            throw new BuildException("Load resource failed: " + resource, e);
        }
        finally {
            if (reader!=null) {
                try {
                    reader.close();
                }
                catch (IOException e) {}
            }
        }
    }
}
